<template>
    <el-dialog v-model="dialogVisible" :title="winTitle" :close-on-click-modal="false" append-to-body width="80%"
        class="editDialog" align-center>

        <el-form inline class="basicForm" label-position="right" :model="formData" ref="formRef" :rules="rules"
            height="300px" label-width="120px">
            <el-form-item label="测点名称" style="width: 100%;" prop="projectName" required>
                <el-input v-model="formData.projectName"></el-input>
            </el-form-item>

        </el-form>

        <div style="width: 100%; height: calc(100vh * 0.8); margin-bottom: 10px;display: flex; flex-direction: column;">
            <MultiImgMarker v-model:modelValue="dots" :img-list="formData.pics" :max-markers="1" />
        </div>

        <template #footer>
            <el-button @click="dialogVisible = false" auto-insert-space>取消</el-button>
            <el-button type="primary" @click="onConfirm" auto-insert-space>确定</el-button>
        </template>


    </el-dialog>

</template>

<script setup lang="js">

import { ref, defineProps, reactive } from 'vue'
import { ElMessage } from "element-plus";
import MultiImgMarker from '@/components/MultiImgMarker.vue'

import { projectSave } from "@/utils/requests";
import { no } from 'element-plus/es/locales.mjs';

let dialogVisible = ref(false);

let formRef = ref();

const emits = defineEmits(["confirm"]);

let isEdit = ref(false);

let winTitle = ref("");

// 规则：trigger 千万别省
const rules = reactive({
    objName: [
        { required: true, message: '请输入测点名称', trigger: 'blur' }   // trigger 必写
    ]
})

/* 1. 初始值常量 */
const initialForm = () => ({
    id: null,
    parentId: null,
    projectName: "",
    pics: [],
    remark: "",
})

let formData = reactive(initialForm());


const dots = ref([
])


const openDialog = (node) => {
    dialogVisible.value = true;

    formData.pics = [];

    dots.value = [];

    if (node.level === 2) {
        winTitle.value = "新增测点";

        Object.keys(formData).forEach(k => delete formData[k]);

        Object.assign(formData, initialForm());

        formData.parentId = node.data.id;

        node.data.ext?.attachs.forEach(item => {
            formData.pics.push({ id: item.attachId, name: item.name, url: item.img })
        });

        isEdit.value = false;
    } else {
        winTitle.value = "编辑测点";

        Object.assign(formData, node.data);

        node.parent.data.ext?.attachs.forEach(item => {
            formData.pics.push({ id: item.attachId, name: item.name, url: item.img })
        });

        if (node.data.ext) {
            dots.value.push({ imgId: node.data.ext.attachId, imgUrl: '', markers: [{ id: Date.now(), x: parseFloat(node.data.ext.leftTop.split(',')[0]), y: parseFloat(node.data.ext.leftTop.split(',')[1]) }], marks: node.data.ext.marks ? JSON.parse(node.data.ext.marks) : [] })
        }

        isEdit.value = true;
    }



}

const onConfirm = () => {
    formRef.value.validate((valid, fields) => {
        if (valid) { 
            const fd = new FormData()
            if (formData.id) fd.append('id', formData.id)
            fd.append("parentId", formData.parentId)
            fd.append('projectName', formData.projectName)
            if (formData.remark) fd.append('remark', formData.remark)

            if (dots.value.length > 0) {
                  let lastDot = dots.value[dots.value.length - 1];

                let attch = formData.pics.find(item => item.id === lastDot.imgId);
                if (attch) {
                    fd.append('relJson', JSON.stringify({ attachId: attch.id, adId: formData.ext?.adId, leftTop: lastDot.markers[0].x + "," + lastDot.markers[0].y }));  // 已上传的图片只传ID

                    attch.marks = lastDot.marks;
                } 
            }

            projectSave(fd).then((data) => {
                if (data) {
                    emits("confirm");

                    ElMessage.success("保存成功");

                    dialogVisible.value = false;
                } else {
                    ElMessage.error("保存失败");
                }
            });
        } else {
            const firstMsg = Object.keys(fields)
                .map(k => fields[k][0]?.message)
                .find(Boolean)

            ElMessage.error(firstMsg)

            return false;
        }
    });

};


defineExpose({ openDialog });
</script>

<style scoped>
.thumb img {
    width: 60px;
    height: 60px;
    margin: 4px;
    cursor: pointer;
    border: 2px solid transparent;
}

.thumb img.active {
    border-color: #409eff;
}

.fill {
    --v-marker-width: 100%;
    --v-marker-height: 100%;
}
</style>
